<template>
    <div class="goods-list-container">
        <!-- 查询表单 -->
        <el-card shadow="never" class="search-card">
            <el-form :model="searchForm" label-width="100px" size="medium">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="商品ID">
                            <el-input v-model="searchForm.id" placeholder="请输入商品ID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="商品名称">
                            <el-input v-model="searchForm.name" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="商品分类">
                            <el-cascader v-model="searchForm.typeIds" :options="categoryOptions"
                                :props="{ value: 'id', label: 'name', children: 'children' }" placeholder="请选择分类"
                                clearable></el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="品牌">
                            <el-input v-model="searchForm.brand" placeholder="请输入品牌"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="存储条件">
                            <el-select v-model="searchForm.storeConditionId" placeholder="请选择" clearable>
                                <el-option v-for="item in storeConditions" :key="item.id" :label="item.store"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="商品规格">
                            <el-input-number v-model="searchForm.size" controls-position="right"
                                :value="null"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="规格单位">
                            <el-select v-model="searchForm.unitId" placeholder="请选择" clearable>
                                <el-option v-for="item in units" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="商品状态">
                            <el-select v-model="searchForm.status" placeholder="请选择" clearable>
                                <el-option label="上架" :value="1"></el-option>
                                <el-option label="下架" :value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="原价">
                            <el-col :span="11">
                                <el-input-number v-model="searchForm.originPriceMin" :min="0" :precision="2"
                                    controls-position="right" placeholder="最低价"></el-input-number>
                            </el-col>
                            <el-col :span="2" style="text-align: center">-</el-col>
                            <el-col :span="7">
                                <el-input-number v-model="searchForm.originPriceMax" :min="0" :precision="2"
                                    controls-position="right" placeholder="最高价"></el-input-number>
                            </el-col>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="现价">
                            <el-col :span="7">
                                <el-input-number v-model="searchForm.priceMin" :min="0" :precision="2"
                                    controls-position="right" placeholder="最低价"></el-input-number>
                            </el-col>
                            <el-col :span="2" style="text-align: center">-</el-col>
                            <el-col :span="7">
                                <el-input-number v-model="searchForm.priceMax" :min="0" :precision="2"
                                    controls-position="right" placeholder="最高价"></el-input-number>
                            </el-col>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" class="button-group">
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 商品列表 -->
        <el-card shadow="never" class="table-card">
            <div class="table-header" style="text-align: end;">
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增商品</el-button>
            </div>

            <el-table :data="tableData" border style="width: 100%" v-loading="loading">
                <el-table-column prop="id" label="商品ID" width="90"></el-table-column>
                <el-table-column prop="name" label="商品名称" width="160"></el-table-column>
                <el-table-column prop="typeFirstName" label="一级分类" width="100"></el-table-column>
                <el-table-column prop="typeSecondName" label="二级分类" width="100"></el-table-column>
                <el-table-column prop="brand" label="品牌" width="120"></el-table-column>
                <el-table-column label="规格" width="120">
                    <template slot-scope="scope">
                        约 {{ scope.row.size }} 克/{{ scope.row.unitName }}
                    </template>
                </el-table-column>
                <el-table-column prop="storeConditionName" label="存储条件" width="180"></el-table-column>
                <el-table-column label="价格" width="120">
                    <template slot-scope="scope">
                        <span style="text-decoration: line-through; color: #999; margin-right: 5px"
                            v-if="scope.row.originPrice">
                            ¥{{ scope.row.originPrice }}
                        </span>
                        <span style="color: #f56c6c; font-weight: bold">¥{{ scope.row.price }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" width="80"></el-table-column>
                <el-table-column label="状态" width="80">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                            {{ scope.row.status === 1 ? '上架' : '下架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)">详情&编辑</el-button>
                        <el-button size="mini" :type="scope.row.status === 1 ? 'danger' : 'success'"
                            @click="handleStatusChange(scope.row)">
                            {{ scope.row.status === 1 ? '下架' : '上架' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pagination.pageNum" :page-sizes="[5, 10, 20, 50, 100]" :page-size="pagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
            </el-pagination>
        </el-card>

        <!-- 新增商品弹窗 -->
        <el-dialog title="新增商品" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商品名称" prop="name">
                            <el-input v-model="addForm.name" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品分类" prop="typeIds">
                            <el-cascader v-model="addForm.typeIds" :options="categoryOptions"
                                :props="{ value: 'id', label: 'name', children: 'children' }" placeholder="请选择分类"
                                clearable style="width: 100%"></el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="品牌" prop="brand">
                            <el-input v-model="addForm.brand" placeholder="请输入品牌"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品描述" prop="description">
                            <el-input v-model="addForm.description" placeholder="请输入商品描述" type="textarea"
                                :rows="2"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="规格" prop="size">
                            <el-input-number v-model="addForm.size" controls-position="right" :min="0" :precision="2"
                                style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单位" prop="unitId">
                            <el-select v-model="addForm.unitId" placeholder="请选择单位" style="width: 100%" clearable>
                                <el-option v-for="item in units" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="存储条件" prop="storeConditionId">
                            <el-select v-model="addForm.storeConditionId" placeholder="请选择存储条件" style="width: 100%"
                                clearable>
                                <el-option v-for="item in storeConditions" :key="item.id" :label="item.store"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库存" prop="stock">
                            <el-input-number v-model="addForm.stock" controls-position="right" :min="0"
                                style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="原价" prop="originPrice">
                            <el-input-number v-model="addForm.originPrice" controls-position="right" :min="0"
                                :precision="2" style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="现价" prop="price">
                            <el-input-number v-model="addForm.price" controls-position="right" :min="0" :precision="2"
                                style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商品状态" prop="status">
                            <el-select v-model="addForm.status" placeholder="请选择状态" style="width: 100%">
                                <el-option label="下架" :value="0"></el-option>
                                <el-option label="上架" :value="1" disabled="true"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="推荐商品" prop="recommend">
                            <el-switch v-model="addForm.recommend" active-value="1" inactive-value="0" active-text="推荐"
                                inactive-text="不推荐"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="推荐理由" prop="reason" v-if="addForm.recommend == 1">
                    <el-input v-model="addForm.reason" placeholder="请输入推荐理由" type="textarea" :rows="2"></el-input>
                </el-form-item>

                <el-form-item label="商品图片" prop="imgSrc">
                    <el-upload action="/api/goods/uploadImg" list-type="picture-card" :on-success="handleUploadSuccess"
                        :before-upload="beforeUpload" :limit="1" :file-list="fileList">
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件, 且不超过2MB</div>
                    </el-upload>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAddForm">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 商品详情/编辑弹窗 -->
        <el-dialog :title="detailDialogTitle" :visible.sync="detailDialogVisible" width="50%" @close="resetDetailForm">
            <el-form :model="detailForm" :rules="detailFormRules" ref="detailFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商品名称" prop="name">
                            <el-input v-model="detailForm.name" placeholder="请输入商品名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品分类" prop="typeIds">
                            <el-cascader v-model="detailForm.typeIds" :options="categoryOptions"
                                :props="{ value: 'id', label: 'name', children: 'children' }" placeholder="请选择分类"
                                clearable style="width: 100%"></el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="品牌" prop="brand">
                            <el-input v-model="detailForm.brand" placeholder="请输入品牌"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="商品描述" prop="description">
                            <el-input v-model="detailForm.description" placeholder="请输入商品描述" type="textarea"
                                :rows="2"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="规格" prop="size">
                            <el-input-number v-model="detailForm.size" controls-position="right" :min="0" :precision="2"
                                style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单位" prop="unitId">
                            <el-select v-model="detailForm.unitId" placeholder="请选择单位" style="width: 100%" clearable>
                                <el-option v-for="item in units" :key="item.id" :label="item.name"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="存储条件" prop="storeConditionId">
                            <el-select v-model="detailForm.storeConditionId" placeholder="请选择存储条件" style="width: 100%"
                                clearable>
                                <el-option v-for="item in storeConditions" :key="item.id" :label="item.store"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库存" prop="stock">
                            <el-input-number v-model="detailForm.stock" controls-position="right" :min="0"
                                style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="原价" prop="originPrice">
                            <el-input-number v-model="detailForm.originPrice" controls-position="right" :min="0"
                                :precision="2" style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="现价" prop="price">
                            <el-input-number v-model="detailForm.price" controls-position="right" :min="0"
                                :precision="2" style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商品状态" prop="status">
                            <el-select v-model="detailForm.status" placeholder="请选择状态" style="width: 100%">
                                <el-option label="下架" :value="0"></el-option>
                                <el-option label="上架" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="推荐商品" prop="recommend">
                            <el-switch v-model="detailForm.recommend" active-value="1" inactive-value="0"
                                active-text="推荐" inactive-text="不推荐"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="推荐理由" prop="reason" v-if="detailForm.recommend == 1">
                    <el-input v-model="detailForm.reason" placeholder="请输入推荐理由" type="textarea" :rows="2"></el-input>
                </el-form-item>

                <el-form-item label="商品图片" prop="imgSrc">
                    <el-upload action="/api/goods/uploadImg" list-type="picture-card"
                        :on-success="handleDetailUploadSuccess" :before-upload="beforeUpload" :limit="1"
                        :file-list="detailFileList" :on-remove="handleDetailRemove">
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件, 且不超过2MB</div>
                    </el-upload>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="detailDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitDetailForm">保 存</el-button>
            </span>
        </el-dialog>
    </div>

</template>

<script>
export default {
    name: 'GoodsList',
    data() {
        return {
            loading: false,
            searchForm: {
                id: null,
                name: '',
                typeIds: [],
                brand: '',
                storeConditionId: null,
                size: null,
                unitId: null,
                status: null,
                priceMin: null,
                priceMax: null,
                originPriceMin: null,
                originPriceMax: null,
            }, // 保存查询商品输入条件
            tableData: [], // 保存查询到的商品信息
            categoryOptions: [], // 分类级联选择器选项
            storeConditions: [], // 存储条件选项
            units: [], // 计量单位选项
            pagination: {
                pageNum: 1,
                pageSize: 10,
                total: 0
            }, // 分页信息
            fileList: [], // 保存图片相关信息

            // 新增弹窗相关数据
            addDialogVisible: false,
            addForm: {
                name: '',
                typeIds: [],
                brand: '',
                description: '',
                size: null,
                unitId: null,
                storeConditionId: null,
                stock: 0,
                originPrice: 0,
                price: 0,
                status: 0,
                recommend: '0',
                reason: '',
                imgSrc: ''
            },
            addFormRules: {
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                typeIds: [
                    { required: true, message: '请选择商品分类', trigger: 'change' }
                ],
                brand: [
                    { required: false, message: '请输入品牌', trigger: 'blur' }
                ],
                size: [
                    { required: true, message: '请输入规格', trigger: 'blur' }
                ],
                unitId: [
                    { required: true, message: '请选择单位', trigger: 'change' }
                ],
                storeConditionId: [
                    { required: true, message: '请选择存储条件', trigger: 'change' }
                ],
                originPrice: [
                    { required: true, message: '请输入原价', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入现价', trigger: 'blur' }
                ]
            },
            // 商品详情弹窗相关数据
            detailDialogVisible: false,
            detailDialogTitle: '商品详情',
            detailForm: {
                id: null,
                name: '',
                typeIds: [],
                brand: '',
                description: '',
                size: null,
                unitId: null,
                storeConditionId: null,
                stock: 0,
                originPrice: 0,
                price: 0,
                status: 1,
                recommend: '0',
                reason: '',
                imgSrc: ''
            },
            detailFormRules: {
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                typeIds: [
                    { required: true, message: '请选择商品分类', trigger: 'change' }
                ],
                brand: [
                    { required: false, message: '请输入品牌', trigger: 'blur' }
                ],
                size: [
                    { required: true, message: '请输入规格', trigger: 'blur' }
                ],
                unitId: [
                    { required: true, message: '请选择单位', trigger: 'change' }
                ],
                storeConditionId: [
                    { required: true, message: '请选择存储条件', trigger: 'change' }
                ],
                originPrice: [
                    { required: true, message: '请输入原价', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入现价', trigger: 'blur' }
                ]
            },
            detailFileList: [],
        }
    },
    created() {
        this.fetchData()
        this.fetchOptions()
    },
    methods: {
        // 获取商品列表数据
        fetchData() {
            this.loading = true
            try {
                const params = {
                    pageNum: this.pagination.pageNum,
                    pageSize: this.pagination.pageSize,
                    param: {
                        ...this.searchForm
                    }
                };

                // 处理分类参数
                if (this.searchForm.typeIds && this.searchForm.typeIds.length === 2) {
                    // 找到选中的分类对象
                    const selectedFirst = this.categoryOptions.find(
                        item => item.id === this.searchForm.typeIds[0]
                    );

                    if (selectedFirst) {
                        const selectedSecond = selectedFirst.children.find(
                            item => item.id === this.searchForm.typeIds[1]
                        );

                        if (selectedSecond) {
                            params.param.typeFirstId = selectedFirst.id;
                            params.param.typeSecondId = selectedSecond.id;
                        }
                    }
                    // 删除前端生成的typeIds，使用后端需要的typeFirstId和typeSecondId
                    delete params.param.typeIds;
                }

                // 删除空值参数（包括价格为0的情况）
                Object.keys(params.param).forEach(key => {
                    // 特殊处理价格相关参数
                    if (key === 'priceMin' || key === 'priceMax' ||
                        key === 'originPriceMin' || key === 'originPriceMax' || key === 'size') {
                        if (params.param[key] === null || params.param[key] === '' || params.param[key] === undefined || params.param[key] === 0) {
                            delete params.param[key]
                        }
                    }
                    // 处理其他参数
                    else if (params.param[key] === null || params.param[key] === '' || params.param[key] === undefined) {
                        delete params.param[key]
                    }
                })

                this.$axios.post('api/goods/queryGoods', params).then(response => {
                    if (response.data.code == 200) {
                        this.tableData = response.data.data.list.map(item => ({
                            ...item,
                            // 处理可能为null的字段
                            id: item.id || '-',
                            name: item.name || item.description.substring(0, 10) + '...'
                        }))
                        this.pagination.total = response.data.data.total
                    } else {
                        this.$message.error(response.msg || '获取数据失败')
                    }
                })
            } catch (error) {
                console.error('请求出错:', error)
                this.$message.error('请求数据失败，请稍后重试')
            } finally {
                this.loading = false
            }
        },

        //  
        fetchOptions() {
            //查询商品分类下拉选项
            this.$axios.get('api/goods/queryTypeToDropdownBox').then(response => {
                if (response.data.code == 200) {
                    this.categoryOptions = this.transformCategoryData(response.data.data);
                } else {
                    this.$message.error(response.msg || '获取分类数据失败');
                }
            }).catch(error => {
                console.error('获取分类数据出错:', error);
                this.$message.error('获取分类数据失败');
            });

            //查询存储条件下拉选项
            this.$axios.get('api/goods/queryStoreConditionToDropdownBox').then(response => {
                if (response.data.code == 200) {
                    this.storeConditions = response.data.data
                        .filter(item => item.status === 1) // 只保留启用的存储条件
                        .map(item => ({
                            id: item.id,
                            store: item.store
                        }));
                } else {
                    this.$message.error(response.msg || '获取存储条件数据失败');
                }
            }).catch(error => {
                console.error('获取存储条件出错:', error);
                this.$message.error('获取存储条件失败');
            });

            // 查询计量单位下拉选项
            this.$axios.get('api/goods/queryUnitToDropdownBox').then(response => {
                if (response.data.code == 200) {
                    this.units = response.data.data
                        .filter(item => item.status === 1) // 只保留启用的单位
                        .map(item => ({
                            id: item.id,
                            name: item.name
                        }));
                } else {
                    this.$message.error(response.msg || '获取单位数据失败');
                }
            }).catch(error => {
                console.error('获取单位数据出错:', error);
                this.$message.error('获取单位数据失败');
            });
        },
        transformCategoryData(rawData) {
            const result = [];
            const firstLevelMap = new Map();

            // 使用后端返回的实际typeFirstId和typeSecondId
            rawData.forEach(item => {
                if (item.nameFirst && !firstLevelMap.has(item.nameFirst)) {
                    firstLevelMap.set(item.nameFirst, {
                        id: item.typeFirstId, // 使用后端返回的typeFirstId
                        name: item.nameFirst,
                        children: []
                    });
                }
            });

            // 处理二级分类
            rawData.forEach(item => {
                if (item.nameFirst && item.nameSecond) {
                    const firstLevel = firstLevelMap.get(item.nameFirst);
                    if (firstLevel) {
                        firstLevel.children.push({
                            id: item.typeSecondId, // 使用后端返回的typeSecondId
                            name: item.nameSecond,
                            originalFirstId: item.typeFirstId // 保留一级分类ID
                        });
                    }
                }
            });

            // 转换为数组并按名称排序
            firstLevelMap.forEach(value => {
                result.push({
                    ...value,
                    children: value.children.sort((a, b) => a.name.localeCompare(b.name))
                });
            });

            return result.sort((a, b) => a.name.localeCompare(b.name));
        },

        // 查询
        handleSearch() {
            this.pagination.pageNum = 1 // 重置页码
            this.fetchData()
        },

        // 重置查询条件
        resetSearch() {
            this.searchForm = {
                id: null,
                name: '',
                typeIds: [],
                brand: '',
                storeConditionId: null,
                size: null,
                unitId: null,
                status: null,
                priceMin: null,
                priceMax: null,
                originPriceMin: null,
                originPriceMax: null,
            }
            this.handleSearch()
        },

        // 分页大小变化
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.pagination.pageNum = 1 // 重置到第一页
            this.fetchData() // 立即触发数据加载
        },

        // 当前页变化
        handleCurrentChange(val) {
            this.pagination.pageNum = val
            this.fetchData()
        },

        // 修改商品状态
        handleStatusChange(row) {
            const newStatus = row.status === 1 ? 0 : 1
            this.$confirm(`确定要${newStatus === 1 ? '上架' : '下架'}该商品吗?`, '提示', {
                type: 'warning'
            }).then(() => {
                this.$axios.get('api/goods/changeGoodsStatus/' + row.id)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.$message.success('操作成功')
                            this.fetchData()
                        }
                    })
            }).catch(() => { })
        },

        // 新增商品弹窗方法
        handleAdd() {
            this.addDialogVisible = true;
        },

        // 重置新增表单
        resetAddForm() {
            this.$refs.addFormRef?.resetFields();
            this.addForm = {
                name: '',
                typeIds: [],
                brand: '',
                description: '',
                size: null,
                unitId: null,
                storeConditionId: null,
                stock: 0,
                originPrice: 0,
                price: 0,
                status: 1,
                recommend: '0',
                reason: '',
                imgSrc: ''
            };
            this.fileList = []; // 清空上传文件列表
        },

        // 上传成功回调
        handleUploadSuccess(response, file, fileList) {
            if (response.code === 200) {
                this.addForm.imgSrc = response.data; // 将返回的图片路径保存到表单
                this.fileList = [{
                    name: file.name,
                    url: response.data // 显示上传成功的图片
                }];
                this.$message.success('图片上传成功');
            } else {
                this.$message.error(response.msg || '图片上传失败');
            }
        },

        // 上传前校验
        beforeUpload(file) {
            const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                this.$message.error('只能上传JPG/PNG图片!');
            }
            if (!isLt2M) {
                this.$message.error('图片大小不能超过2MB!');
            }

            return isImage && isLt2M;
        },

        // 提交新增表单
        submitAddForm() {
            this.$refs.addFormRef.validate(valid => {
                if (valid) {
                    // 检查是否上传了图片
                    if (!this.addForm.imgSrc) {
                        this.$message.warning('请上传商品图片');
                        return;
                    }

                    const params = {
                        ...this.addForm,
                        typeFirstId: this.addForm.typeIds[0],
                        typeSecondId: this.addForm.typeIds[1],
                        imgSrc: this.addForm.imgSrc // 包含图片路径
                    };

                    this.loading = true;
                    this.$axios.post('api/goods/addGoods', params)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('添加商品成功');
                                this.addDialogVisible = false;
                                this.fetchData(); // 刷新列表
                                this.fileList = []; // 清空上传文件列表
                            } else {
                                this.$message.error(response.data.msg || '添加商品失败');
                            }
                        })
                        .catch(error => {
                            console.error('添加商品出错:', error);
                            this.$message.error('添加商品失败');
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                }
            });
        },

        // 编辑商品 - 打开详情弹窗
    handleEdit(row) {
      this.detailDialogTitle = '编辑商品';
      this.loading = true;
      
      // 获取商品详情
      this.$axios.get(`api/goods/queryGoodsById/${row.id}`)
        .then(response => {
          if (response.data.code === 200) {
            const goods = response.data.data;
            this.detailForm = {
              id: goods.id,
              name: goods.name,
              typeIds: [goods.typeFirstId, goods.typeSecondId],
              brand: goods.brand,
              description: goods.description,
              size: goods.size,
              unitId: goods.unitId,
              storeConditionId: goods.storeConditionId,
              stock: goods.stock,
              originPrice: goods.originPrice,
              price: goods.price,
              status: goods.status,
              recommend: goods.recommend ? '1' : '0',
              reason: goods.reason,
              imgSrc: goods.imgSrc
            };
            
            // 设置图片预览
            if (goods.imgSrc) {
              this.detailFileList = [{
                name: '商品图片',
                url: goods.imgSrc
              }];
            }
            
            this.detailDialogVisible = true;
          } else {
            this.$message.error(response.data.msg || '获取商品详情失败');
          }
        })
        .catch(error => {
          console.error('获取商品详情出错:', error);
          this.$message.error('获取商品详情失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 详情弹窗上传成功处理
    handleDetailUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.detailForm.imgSrc = response.data;
        this.detailFileList = [{
          name: file.name,
          url: response.data
        }];
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(response.msg || '图片上传失败');
      }
    },
    
    // 详情弹窗删除图片处理
    handleDetailRemove(file, fileList) {
      this.detailForm.imgSrc = '';
      this.detailFileList = [];
    },
    
    // 重置详情表单
    resetDetailForm() {
      this.$refs.detailFormRef?.resetFields();
      this.detailForm = {
        id: null,
        name: '',
        typeIds: [],
        brand: '',
        description: '',
        size: null,
        unitId: null,
        storeConditionId: null,
        stock: 0,
        originPrice: 0,
        price: 0,
        status: 0,
        recommend: '',
        reason: '',
        imgSrc: ''
      };
      this.detailFileList = [];
    },
    
    // 提交详情表单（更新商品）
    submitDetailForm() {
      this.$refs.detailFormRef.validate(valid => {
        if (valid) {
          const params = {
            ...this.detailForm,
            typeFirstId: this.detailForm.typeIds[0],
            typeSecondId: this.detailForm.typeIds[1]
          };
          
          this.loading = true;
          this.$axios.post('api/goods/updateGoods', params)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success('更新商品成功');
                this.detailDialogVisible = false;
                this.fetchData(); // 刷新列表
              } else {
                this.$message.error(response.data.msg || '更新商品失败');
              }
            })
            .catch(error => {
              console.error('更新商品出错:', error);
              this.$message.error('更新商品失败');
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    }
}
</script>

<style scoped>
.goods-list-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.table-card {
    margin-bottom: 20px;
}

.table-header {
    margin-bottom: 15px;
}

.pagination {
    margin-top: 15px;
    text-align: right;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    padding-top: 5px;
}

/* 新增弹窗样式 */
.el-dialog__body {
    padding: 20px;
}

.el-form-item {
    margin-bottom: 20px;
}

.el-upload__tip {
    margin-top: 5px;
    color: #999;
}
</style>